<?php

namespace App\Admin\Http\Controllers\System;

use Flash;
use App\Admin\Eloquent\CodeType;
use App\Admin\Http\Requests\CodeTypeRequest;
use App\Admin\Http\Controllers\Controller;
use App\Extensions\Pagination\BootstrapThreePresenter;
use Illuminate\Http\Request;

class CodeTypesController extends Controller
{
	/**
     * 查询代码类别信息
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $query = $request->only('search');

        $codeTypes = CodeType::paginateQuery($query);

        if (!empty($query)) {
            $codeTypes->appends($query);
        }

        // 分页
        $links = (new BootstrapThreePresenter($codeTypes))->render();

        return view('admin.system.code_types.index', compact('codeTypes', 'links', 'query'));
    }

	/**
     * 新增代码信息表单
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.system.code_types.create');
    }

    /**
     * 新增代码类别信息
     *
     * @param  \App\Admin\Http\Requests\CodeTypeRequest  $request
     * @return \Illuminate\Http\Response
     */
    public function store(CodeTypeRequest $request)
    {
        $codeType = new CodeType($request->input());

        $codeType->save();
        
        Flash::success('新增代码类别信息成功');

        return $this->redirectAction('System\CodeTypesController@index');
    }

    /**
     * 编辑代码信息表单
     *
     * @param  mixed $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $codeType = $this->codeType($id);

        return view('admin.system.code_types.edit', compact('codeType'));
    }

    /**
     * 编辑代码类别信息
     *
     * @param  mixed $id
     * @param  \App\Admin\Http\Requests\CodeTypeRequest  $request
     * @return \Illuminate\Http\Response
     */
    public function update($id, CodeTypeRequest $request)
    {
        $codeType = $this->codeType($id);

        $codeType->update($request->only('name', 'description'));
        
        Flash::success('编辑代码类别信息成功');

        return $this->redirectAction('System\CodeTypesController@index');
    }

    /**
     * 删除代码类别信息
     *
     * @param  mixed $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $codeType = $this->codeType($id);

        $codeType->delete();
        
        Flash::success('删除代码类别信息成功');

        return $this->redirectAction('System\CodeTypesController@index');
    }

    /**
     * 通过 id 查找代码类别
     * 
     * @param  mixed  $id
     * @return \App\Admin\Eloquent\CodeType]
     */
    protected function codeType($id)
    {
        return CodeType::findOrFail($id);
    }
}